package com.cnsugar.facerecgonized;

import com.alibaba.fastjson.JSON;
import com.cnsugar.ai.face.SeetafaceBuilder;
import com.cnsugar.ai.face.bean.Result;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


/**
 * @Author ChenZhangKun
 * @Date 2020/4/16 14:39
 */
@SuppressWarnings("all")
public class FaceRe {
    // 记录比对总数
    int i = 0;
    // 创建集合，存储人脸库
    public static volatile List<BufferedImage> imageList = new LinkedList<>();
    // 创建集合，存储客户端流
   // public static volatile List<Socket> socketList = new LinkedList<>();
    // 创建集合，存出结果
    public static volatile List<String> listResult = new LinkedList<>();
    //初始化，监听端口
    public static ServerSocket serverSocket;
    // 添加map存储发送者信息
    public static volatile Map<BufferedImage,String> map=new HashMap<>(10);
    // 添加map存储比对完成信息
    public static volatile  Map<String,String> mapResult=new HashMap<>(10);
    static {
        try {
            Properties prop = SeetafaceBuilder.getConfig();
            // 监听客户端发送图片的接口
            String port = prop.getProperty("listen.port");
            int iPort = Integer.parseInt(port);
            serverSocket = new ServerSocket(iPort);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 加载人脸库到内存
    public void init() {
        //系统启动时先调用初始化方法
        // 先加载dll开发包，加载完成后新开线程去加载数据库的人脸数据进入内存
        SeetafaceBuilder.build();
        //等待初始化完成
        while (SeetafaceBuilder.getFaceDbStatus() == SeetafaceBuilder.FacedbStatus.LOADING || SeetafaceBuilder.getFaceDbStatus() == SeetafaceBuilder.FacedbStatus.READY) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    // 新开线程，发送回数据
    public void sendBack() {
        // 线程方式
        SendResult sendResult=new SendResult();
        // 线程池方式
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(sendResult);
    }

    // 拿到人脸进行比对
    public void faceR() {
        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        // 创建线程
        FaceRecognizedThread faceRecognizedThread = new FaceRecognizedThread();
        // 监控缓冲列表中是否有缓存存在
        while (true) {
            if (map != null && map.size() > 0) {
                System.out.println(imageList.get(0));
                Future future = executorService.submit(faceRecognizedThread);
                long l = System.currentTimeMillis();
                try {
                    Result result = (Result) future.get();
                    if (result != null) {
                        String name = result.getKey();
                        name = name.substring(0, name.length() - 4);
//                        System.out.println("====");
//                        System.out.println("名字是" + name);
//                        System.out.println("相似度" + result.getSimilar());
//                        System.out.println("搜索结果：" + result + "， 耗时：" + (System.currentTimeMillis() - l));
//                        System.out.println(++i);
//                        System.out.println("====");
                        // 写回数据
                        // 将result得到结果封装缓存
                        SearchResult searchResult = new SearchResult(name, result.getSimilar(),result.getHost(),null);
                        // 搜索耗时
                        System.out.println("搜索结果：" + result + "， 耗时：" + (System.currentTimeMillis() - l));
                        // 转为json传输
                        String string = JSON.toJSONString(searchResult);
                        listResult.add(string);
                        // 添加到map中
                        mapResult.put(result.getHost(),string);
                    } else {
//                        System.out.println("====");
//                        System.out.println("没有找到这个人");
//                        System.out.println("耗时"+"  "+(System.currentTimeMillis()-l));
//                        System.out.println(++i);
//                        System.out.println("====");
                        // 写回数据\
                        // 没有结果，相似度为0
                        SearchResult searchResult = new SearchResult("null", 0.0f,result.getHost(),result.getBufferedImage());
                        System.out.println("搜索结果：" + result + "， 耗时：" + (System.currentTimeMillis() - l));
                        String string = JSON.toJSONString(searchResult);
                        listResult.add(string);
                       // FaceRe.socketList.remove(0);
                        // 添加到map中
                        // 将比对结果存到结果集中
                        mapResult.put(result.getHost(),string);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            } else {
                continue;
            }

        }
    }
}
